package com.eqdd.yiqidian.ui.companyspace

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.EquipmentBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.utils.ImageUtil
import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.activity_recyclerview_refresh.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.util.*

/**
 * Created by jhj on 18-6-27.
 */
class EquipmentListActivity : BaseActivity() {

    private var mvcHelper: MVCCoolHelper<List<EquipmentBean>>? = null
    private var pageNum: Int = 0
    private var slimAdapterEx: SlimAdapterEx<EquipmentBean>? = null
    override fun initBinding() {
        setContentView(R.layout.activity_recyclerview_refresh)
        initTopTitleBar(View.VISIBLE, "设备信息")
    }

    override fun initData() {
        val companyId = if (intent.getIntExtra(Config.TYPE, 0) == 0) {
            user.companyId
        } else {
            val id = intent.getIntExtra(Config.COMPANY_ID, 0)
            if (id == 0) {
                finish()
                toast("获取信息失败")
            }
            id
        }

        val list = arrayListOf<EquipmentBean>()
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(DividerLineItemDecoration(this))
        slimAdapterEx = SlimAdapterEx.create().register<EquipmentBean>(R.layout.list_item_153, SlimInjector<EquipmentBean> { data, injector ->
            injector
                    ?.with<ImageView>(R.id.iv_image) { view ->
                        if (data?.image != null && "" != data.image) {
                            view.visibility = View.VISIBLE
                            view.onClick {
                                imgPathPreview(data.image)
                            }
                            Glide.with(this@EquipmentListActivity)
                                    .asBitmap()
                                    .apply(ImageUtil.optionsNormal)
                                    .load(data.image)
                                    .into(object : SimpleTarget<Bitmap>() {
                                        override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>) {
                                            val scale = resource.width.toDouble() / resource.height.toDouble()
                                            if (scale < 0.85 && scale > 0.65) {
                                                view.scaleType = ImageView.ScaleType.CENTER_CROP

                                            }
                                            view.background = BitmapDrawable(resources, resource)
                                        }
                                    })
                        } else {
                            view.visibility = View.GONE
                        }
                    }
                    ?.text(R.id.tv_name, String.format(Locale.CHINA, "设备名称：%s", data?.equipmentName))
                    ?.text(R.id.tv_post, String.format(Locale.CHINA, "生产厂商：%s", data?.manufactor))
                    ?.text(R.id.tv_msg, String.format(Locale.CHINA, "购买日期：%s", data?.dateOfPurchase))
        }).attachTo(recyclerView).updateData(list as List<EquipmentBean>?) as SlimAdapterEx<EquipmentBean>?
        ItemClickSupport.addTo(recyclerView).setOnItemClickListener { recyclerView, position, v ->
            startActivityForResult<EquipmentInfoActivity>(Config.UPDATE
                    , Config.ID to slimAdapterEx?.getDataItem(position)?.id
                    , Config.TYPE to intent.getIntExtra(Config.TYPE, 0))
        }


        val dataSource = ModelRx2DataSource<EquipmentBean>(ModelRx2DataSource.OnLoadSource<EquipmentBean> { page, register ->
            pageNum = if (page == 1) 0 else pageNum
            OkGo.post<HttpResult<List<EquipmentBean>>>(HttpConfig.BASE_URL + HttpConfig.EQUIPMENT_LIST)
                    .params("companyId", companyId)
                    .params("page", pageNum)
                    .converter(object : JsonConverter<HttpResult<List<EquipmentBean>>>() {
                        override fun test() {
                            super.test()
                        }
                    }).adapt(FlowableBody<HttpResult<List<EquipmentBean>>>())
                    .flatMap({ result ->
                        if (page == 1) {
                            mvcHelper?.setAutoLoadMore(true)
                        }
                        pageNum = result.page
                        Flowable.just<MutableList<EquipmentBean>>(if (result.items == null) ArrayList() else result.items as MutableList<EquipmentBean>?)
                    })
        }, 10)

        mvcHelper = MVCCoolHelper<List<EquipmentBean>>(coolRefreshView)
        mvcHelper?.setDataSource(dataSource)
        mvcHelper?.adapter = slimAdapterEx
        mvcHelper?.refresh()
    }

    override fun setView() {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                Config.UPDATE,
                Config.ADD -> mvcHelper?.refresh()

            }
        }
    }


}